package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.NewsMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 考核5. 	新闻新增
 *
 * @author 周涛
 */
@Order(5)
@Service
public class Judge_5 implements GetJudgeIpResultService {

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private NewsMapper newsMapper;

    @Override
    public StudentResult getJudgeIpResult(String ip) {
        StudentResult studentResult = new StudentResult();
        studentResult.setItemNumber("5");

        try {
            // 测试正常新增新闻
            boolean normalAddTest = testNormalNewsAdd(ip);
            if (!normalAddTest) {
                studentResult.setScore(0.0);
                studentResult.setResult("正常新增新闻测试失败");
                return studentResult;
            }
            studentResult.setScore(2.0);
            studentResult.setResult("新闻新增功能测试通过");

        } catch (Exception e) {
            studentResult.setScore(0.0);
            studentResult.setResult("接口调用异常：" + e.getMessage());
            e.printStackTrace();
        }

        return studentResult;
    }

    // 测试正常新增新闻
    private boolean testNormalNewsAdd(String ip) throws Exception {
        String url = "http://" + ip.trim() + "/news/insert";
        System.out.println("测试URL: " + url);

        // 设置请求头
        Map<String, String> headers = new HashMap<>();

        // 构建请求体
        long timestamp = System.currentTimeMillis();
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("newsTypeId", "1");
        requestMap.put("title", "测试新闻标题_" + timestamp);
        requestMap.put("text", "这是一条测试新闻内容");

        String result = httpUtil.doPost(url, headers, requestMap);
        if (result == null) {
            return false;
        }

        JSONObject json = JSONObject.parseObject(result);
        if (json.getIntValue("code") != 200) {
            return false;
        }

        return true;
    }

}